/**
 * 定义页面对应的后台处理类完整路径。
 */
var clsUrl = basePath + 'JarpListener?className=cn.com.zsc.income.EmpSalaryManage';

Ext.onReady(function(){
	Ext.QuickTips.init();
		
	/**
	 * 工资月份控件
	 */
	var salaryDate = new Ext.form.DateField({
		id:'salaryDate',
        fieldLabel:"工资月份",
        name:'salaryDate',
        format:'Y-m',
        editable:false,
        width:90,
        listeners:{
        	'render':function() {
        		var now = new Date();
        		
        		/*
        		 * 设置当前月份
        		 */
				var year = now.getYear();
				var month = now.getMonth() + 1;

				var salaryDate = year;
				salaryDate += ((month < 10) ? "-0" : "-") + month+"";
				
				Ext.getCmp("salaryDate").setValue(salaryDate);
        	}
        }
    });
    
	var storereader= new Ext.data.JsonReader({
    	fields:[
    		{name :'SERIALNUMBER'},
    		{name :'ID'},
    		{name :'DATE'},
    		{name :'GUIDEID'},
    		{name :'GUIDENAME'},
    		{name :'DEPT'},
    		{name :'BANKNO'},
    		{name :'BASIC'},
    		{name :'POST'},
    		{name :'WORKAGE'},
    		{name :'EFFICIENT'},
    		{name :'TRAFFIC'},
    		{name :'LUNCH'},
    		{name :'CAR'},
    		{name :'INSURANCE'},
    		{name :'ALLOWANCE'},
    		{name :'OTHER'},
    		{name :'STOTAL'},
    		{name :'TAX'},
    		{name :'DINSURANCE'},
    		{name :'DSICK'},
    		{name :'DLEFT'},
    		{name :'DTOTAL'},
    		{name :'ATOTAL'},
    		{name :'REMARKED'},
    		
    		{name :'SHOW_DEPT'}
    	]
	});
		
	/**
	 * 查询员工数据
	 */
	var store = new Ext.data.Store({
		reader:storereader
	});
	
    var searchPanel = new Ext.Panel({
		id:"searchPanel",
		region:"north",
		border:false,
		layout : 'column',
		labelAlign : 'right',
		height:40,
		frame:true,
		labelWidth : 80,
		items:[{
			layout : 'form',
			border:false,
		  	labelWidth : 40,
		  	labelAlign : 'right',
		  	columnWidth : .17,
		  	items:[{fieldLabel : '工号',width : 100,name : 'guideID',id : 'guideID',xtype : 'textfield'}]
		},{
			layout : 'form',
		  	labelWidth : 40,
		  	labelAlign : 'right',
		  	columnWidth : .17,
		  	items:[{fieldLabel : '姓名',width : 100,name : 'guideName',id : 'guideName',xtype : 'textfield'}]
		},{
			layout : 'form',
		  	labelWidth : 60,
		  	labelAlign : 'right',
		  	columnWidth : .20,
		  	items:[salaryDate]
		},{
			layout : 'form',
		  	labelWidth : 0,
		  	labelAlign : 'right',
		  	columnWidth : .25,
		  	items:[{
	  			layout : 'column',
				labelAlign : 'right',
				items:[{
					layout : 'form',
				  	labelWidth : 10,
				  	labelAlign : 'right',
				  	columnWidth : .33,
				  	items:[
				  		{xtype:'button',width:70,height:25,text:'查询',handler:search}
				  	]
				},{
					layout : 'form',
				  	labelWidth : 10,
				  	labelAlign : 'right',
				  	columnWidth : .33,
				  	items:[
				  		{xtype:'button',width:70,height:25,text:'重置',handler:function() {
				  				Ext.getCmp("workID").setValue("");
				  				Ext.getCmp("eName").setValue("");
					  			
					  			var now = new Date();
        	
								var year = now.getYear();
								var month = now.getMonth() + 1;
								var day = now.getDate();
				
								var guideDate = year;
								guideDate += ((month < 10) ? "-0" : "-") + month+"";
								guideDate += ((day < 10) ? "-0" : "-") + day+"";
								
								Ext.getCmp("guideDate").setValue(guideDate);
							}
						}
				    ]
				},{
					layout : 'form',
				  	labelWidth : 10,
				  	labelAlign : 'right',
				  	columnWidth : .34,
				  	items:[{xtype:'button',width:70,height:25,text:'导出Excel',handler:exportExcel}]
				}]
			}]
		}],
		keys: {
            key: 13,
            fn: search
        }
	});
	
	/**
	 * 用户列表
	 */
	var basegrid = new Ext.grid.EditorGridPanel( {
		id :'basegrid',
		store :store,
		split :true,
		bodyStyle:'5px 15px 0',
		region :'center',
		border :false,
		enableColumnMove:false,                                           
	  	enableHdMenu:false,
		frame :false,
		autoScroll :true,
    	columns: [
            {header:'编号',enableColumnMove:false,sortable:true,hidden:true,hideCollapseTool:false, enableHdMenu:false,enableColumnResize :false,dataIndex: 'ID'},
            {header:'序号',width:40,enableColumnMove:false,sortable:true,hideCollapseTool:false, enableHdMenu:false,enableColumnResize :false,dataIndex:'SERIALNUMBER'},
            {header:'导游编号',width:60,enableColumnMove:false,sortable:true,hideCollapseTool:false, enableHdMenu:false,enableColumnResize :false,dataIndex: 'GUIDEID'},
          	{header:'部门',width:60,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'SHOW_DEPT'},
          	{header:'姓名',width:70,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'GUIDENAME'},
          	{header:'发放时间',width:100,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'DATE',editor:new Ext.form.DateField()},
          	{header:'银行帐号',width:140,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'BANKNO',editor:new Ext.form.NumberField()},
          	{header:'基础工资',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'BASIC',editor:new Ext.form.NumberField()},
          	{header:'岗位工资',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'POST',editor:new Ext.form.NumberField()},
          	{header:'工龄工资',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'WORKAGE',editor:new Ext.form.NumberField()},
			{header:'绩效工资',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'EFFICIENT',editor:new Ext.form.NumberField()},
			{header:'交通费',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'TRAFFIC',editor:new Ext.form.NumberField()},
			{header:'误餐费',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'LUNCH',editor:new Ext.form.NumberField()},
			{header:'出车费',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'CAR',editor:new Ext.form.NumberField()},
			{header:'保险费',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'INSURANCE',editor:new Ext.form.NumberField()},
			{header:'特岗津贴',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'ALLOWANCE',editor:new Ext.form.NumberField()},
			{header:'其他',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'OTHER',editor:new Ext.form.NumberField()},
			{header:'应发合计',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'STOTAL'},
			{header:'本次扣税',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'TAX',editor:new Ext.form.NumberField()},
          	{header:'代扣保险费',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'DINSURANCE',editor:new Ext.form.NumberField()},
          	{header:'病假扣款',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'DSICK',editor:new Ext.form.NumberField()},
          	{header:'事假扣款',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'DLEFT',editor:new Ext.form.NumberField()},
          	{header:'扣款合计',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'DTOTAL'},
          	{header:'实发合计',width:80,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'ATOTAL'},
          	{header:'备注',width:200,sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize:false,dataIndex:'REMARKED',editor:new Ext.form.TextField()}
    	],
    	tbar:[     
      	   	{
	      	   	text:'保存',
	      	   	iconCls:'modify',
	      	   	handler:function(){
      	   			updateSalary();
      	   		}
      	   	}
 	    ],
 	    listeners:{'afteredit':function(obj) {
 	    		var curRecord = obj.record;
 	    		
 	    		if (obj.field == 'BASIC' || obj.field == 'POST' || obj.field == 'WORKAGE'|| obj.field == 'EFFICIENT'
					|| obj.field == 'TRAFFIC'|| obj.field == 'LUNCH' || obj.field == 'CAR'|| obj.field == 'INSURANCE'
						|| obj.field == 'ALLOWANCE' || obj.field == 'OTHER') {
					calculateStotal(curRecord);
				} else if (obj.field == 'TAX' || obj.field == 'DINSURANCE' || obj.field == 'DSICK' || obj.field == 'DLEFT') {
					calculateDtotal(curRecord);
				}
				
				calculateAtotal(curRecord);
 	    	}
 	    }
	});
	
	/**
	 * 计算应发合计 
	 */
	function calculateStotal(curRecord) {
		var basic = curRecord.get("BASIC")=="" ? 0 : curRecord.get("BASIC");
		var post = curRecord.get("POST")=="" ? 0 : curRecord.get("POST");
		var workage = curRecord.get("WORKAGE")=="" ? 0 : curRecord.get("WORKAGE");
		var efficient = curRecord.get("EFFICIENT")=="" ? 0 : curRecord.get("EFFICIENT");
		var traffic = curRecord.get("TRAFFIC")=="" ? 0 : curRecord.get("TRAFFIC");
		var lunch = curRecord.get("LUNCH")=="" ? 0 : curRecord.get("LUNCH");
		var car = curRecord.get("CAR")=="" ? 0 : curRecord.get("CAR");
		var insurance = curRecord.get("INSURANCE")=="" ? 0 : curRecord.get("INSURANCE");
		var allowance = curRecord.get("ALLOWANCE")=="" ? 0 : curRecord.get("ALLOWANCE");
		var other = curRecord.get("OTHER")=="" ? 0 : curRecord.get("OTHER");
		
		var stotal = parseFloat(basic) + parseFloat(post) + parseFloat(workage) + parseFloat(efficient) + parseFloat(traffic) + parseFloat(lunch+car) + parseFloat(insurance) + parseFloat(allowance) + parseFloat(other);
		curRecord.set("STOTAL", stotal);
	}
	
	/**
	 * 计算扣款合计
	 */
	function calculateDtotal(curRecord) {
		var tax = curRecord.get("TAX")=="" ? 0 : curRecord.get("TAX");
		var dinsurance = curRecord.get("DINSURANCE")=="" ? 0 : curRecord.get("DINSURANCE");
		var dsick = curRecord.get("DSICK")=="" ? 0 : curRecord.get("DSICK");
		var dleft = curRecord.get("DLEFT")=="" ? 0 : curRecord.get("DLEFT");
		
		var dtotal = parseFloat(tax) + parseFloat(dinsurance) + parseFloat(dsick) + parseFloat(dleft);
		curRecord.set("DTOTAL", dtotal);
	}
	
	/**
	 * 计算实发合计
	 */
	function calculateAtotal(curRecord) {
		var stotal = curRecord.get("STOTAL")=="" ? 0 : curRecord.get("STOTAL");
		var dtotal = curRecord.get("DTOTAL")=="" ? 0 : curRecord.get("DTOTAL");
		
		var atotal = parseFloat(stotal) - parseFloat(dtotal);
		
		curRecord.set("ATOTAL", atotal);
	}
	
	/**
	 * 更新薪资记录 
	 */
	function updateSalary() {
		var modifyRecord = store.getModifiedRecords();
		
		if (modifyRecord.length == 0) {
			Ext.Msg.show({
				title : '提示',
				width : 210,
				msg : '请先修改数据!',
				buttons : Ext.Msg.OK,
				icon : Ext.Msg.ERROR
			});
			return;
		}
		
		mainPanel.body.mask('正在保存，请稍等', 'x-mask-loading');
		var obj;
		var recordModStr = "[";
		
		for (var i=0; i<modifyRecord.length; i++) {
			obj = new Object();
			obj.id = modifyRecord[i].data.ID;
			obj.date = modifyRecord[i].data.DATE;
			obj.guideID = modifyRecord[i].data.GUIDEID;
			obj.guideName = modifyRecord[i].data.GUIDENAME;
			obj.dept = modifyRecord[i].data.DEPT;
			obj.bankno = modifyRecord[i].data.BANKNO;
			obj.basic = modifyRecord[i].data.BASIC;
			obj.post = modifyRecord[i].data.POST;
			obj.workage = modifyRecord[i].data.WORKAGE;
			obj.efficient = modifyRecord[i].data.EFFICIENT;
			obj.traffic = modifyRecord[i].data.TRAFFIC;
			obj.lunch = modifyRecord[i].data.LUNCH;
			obj.car = modifyRecord[i].data.CAR;
			obj.insurance = modifyRecord[i].data.INSURANCE;
			obj.allowance = modifyRecord[i].data.ALLOWANCE;
			obj.other = modifyRecord[i].data.OTHER;
			obj.stotal = modifyRecord[i].data.STOTAL;
			obj.tax = modifyRecord[i].data.TAX;
			obj.dinsurance = modifyRecord[i].data.DINSURANCE;
			obj.dsick = modifyRecord[i].data.DSICK;
			obj.dleft = modifyRecord[i].data.DLEFT;
			obj.dtotal = modifyRecord[i].data.DTOTAL;
			obj.atotal = modifyRecord[i].data.ATOTAL;
			obj.remarked = modifyRecord[i].data.REMARKED;
			
			recordModStr += Ext.util.JSON.encode(obj);
			
			if(i < modifyRecord.length - 1) {
				recordModStr += ",";   
			}
		}
		
		recordModStr += "]";
		
		var url=clsUrl+'&methodName=updateEmpSalary&paramCount=0'
		
    	httpReq=null;
		httpReq = getXMLHttpRequest();
    	httpReq.onreadystatechange = onUpdateRtn;
		httpReq.open("POST",url, true);
		httpReq.send(recordModStr);
	}
	
	function onUpdateRtn(){
		if(httpReq.readyState == 4){
		   	if(httpReq.status == 200){
		   		if(httpReq.responseText == "success"){
		   			Ext.Msg.show({   
		    	   		title : '成功提示',
		    	   		width:200,
		   				msg : '保存成功！',  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.INFO   
		   			});
					
		   			store.commitChanges();
		   			search();
		   			mainPanel.body.unmask();
		   			
		   			httpReq=null;
		   		}else{
		   			Ext.Msg.show({   
		    	   		title : '错误提示',
		    	   		width:200,
		   				msg : httpReq.responseText,  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.ERROR   
		   			});  
		   			httpReq=null;
		   		}
		   	}
		}
	}

	var mainPanel = new Ext.Panel({
            id: 'mainPanel',
            region:'center',
            split:true,
            border:false,
            frame:true,
            layout: 'border',  
            items:[searchPanel,basegrid]
    });
    
	var viewport = new Ext.Viewport( {
		layout:'border',
		items: [mainPanel]
	});
	
	/**
	 * 查询数据
	 */
	function search(){	
		mainPanel.body.mask('正在加载数据...','x-mask-loading');
		
		var obj = new Object();
		obj.guideID = Ext.getCmp("guideID").getValue();
		obj.guideName = Ext.getCmp("guideName").getValue();
		obj.salaryDate = Ext.getCmp("salaryDate").getRawValue();
		
    	var url=clsUrl+'&methodName=getEmpSalary&paramCount=0'
		Ext.http.send(url,function(res){
			basegrid.store.loadData(Ext.decode(res));
			mainPanel.body.unmask();
		},Ext.encode(obj));
	}
	
	/**
	 * 当没有薪资数据时初始化数据
	 */
	function initializeSalary() {
		var url=clsUrl+'&methodName=initializeSalary&paramCount=0'
		
    	httpReq=null;
		httpReq = getXMLHttpRequest();
    	httpReq.onreadystatechange = onInitializaRtn;
		httpReq.open("POST",url, true);
		httpReq.send();
	}
	
	function onInitializaRtn() {
		if(httpReq.readyState == 4){
		   	if(httpReq.status == 200){
		   		if(httpReq.responseText != "success"){
		   			Ext.Msg.show({   
		    	   		title : '错误提示',
		    	   		width:200,
		   				msg : httpReq.responseText,  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.ERROR   
		   			});  
		   			httpReq=null;
		   		} else {
		   			search();
		   		}
		   	}
		}
	}
	
	/**
	 * 导出薪资报表
	 */
	function exportExcel() {
		var vExportContent = basegrid.getExcelXml(); // 获取数据
		if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8 || Ext.isSafari || Ext.isSafari2 || Ext.isSafari3) { // 判断浏览器
			var fd = Ext.get('frmDummy');
			if (!fd) {
				fd = Ext.DomHelper.append(Ext.getBody(), {
							tag : 'form',
							method : 'post',
							id : 'frmDummy',
							action : exportUrl,
							target : '_blank',
							name : 'frmDummy',
							cls : 'x-hidden',
							cn : [{
										tag : 'input',
										name : 'exportContent',
										id : 'exportContent',
										type : 'hidden'
									}]
						}, true);
			}
			fd.child('#exportContent').set({
						value : vExportContent
					});
			fd.dom.submit();
		} else {
			document.location = 'data:application/vnd.ms-excel;base64,'+ Base64.encode(vExportContent);
		}
	}
	
	initializeSalary();
});